package cn.iocoder.yudao.framework.common.util.string;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 字符串工具类
 *
 * @author 芋道源码
 */
@Slf4j
public class StrUtils {

    public static String maxLength(CharSequence str, int maxLength) {
        return StrUtil.maxLength(str, maxLength - 3); // -3 的原因，是该方法会补充 ... 恰好
    }

    /**
     * 给定字符串是否以任何一个字符串开始
     * 给定字符串和数组为空都返回 false
     *
     * @param str      给定字符串
     * @param prefixes 需要检测的开始字符串
     * @since 3.0.6
     */
    public static boolean startWithAny(String str, Collection<String> prefixes) {
        if (StrUtil.isEmpty(str) || ArrayUtil.isEmpty(prefixes)) {
            return false;
        }

        for (CharSequence suffix : prefixes) {
            if (StrUtil.startWith(str, suffix, false)) {
                return true;
            }
        }
        return false;
    }

    public static List<Long> splitToLong(String value, CharSequence separator) {
        long[] longs = StrUtil.splitToLong(value, separator);
        return Arrays.stream(longs).boxed().collect(Collectors.toList());
    }

    public static List<Integer> splitToInteger(String value, CharSequence separator) {
        int[] integers = StrUtil.splitToInt(value, separator);
        return Arrays.stream(integers).boxed().collect(Collectors.toList());
    }


    public static String useFirstIfNotNull(String first, String second) {
        if (StrUtil.isNotEmpty(first)) {
            return first;
        }
        return second;
    }

    public static String unicode2String(String unicode) {
        try {
            StringBuilder sb = new StringBuilder();
            int length = unicode.length();
            for (int i = 0; i < length; i++) {
                if ((i + 6) <= length && unicode.charAt(i) == '\\' && unicode.charAt((i + 1)) == 'u') {
                    int data = Integer.parseInt(unicode.substring(i + 2, i + 6), 16);
                    sb.append((char) data);
                    i = i + 5;
                } else {
                    sb.append(unicode.charAt(i));
                }
            }
            return sb.toString();
        } catch (Exception e) {
            log.error("unicode2String error", e);
            return unicode;
        }
    }

}
